package com.hmdp.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hmdp.entity.MessageRecord;
import com.hmdp.entity.MessageStatus;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import java.util.Date;
import java.util.List;

@Mapper
public interface MessageRecordMapper extends BaseMapper<MessageRecord> {
    
    @Update("UPDATE distributed_transaction_message " +
            "SET status = #{status}, update_time = now() " +
            "WHERE message_id = #{messageId}")
    int updateStatus(@Param("messageId") String messageId, @Param("status") Integer status);

    @Update("UPDATE distributed_transaction_message " +
            "SET status = #{status}, " +
            "retry_count = #{retryCount}, " +
            "next_retry_time = #{nextRetryTime}, " +
            "update_time = now() " +
            "WHERE message_id = #{messageId}")
    int updateForRetry(@Param("messageId") String messageId,
                       @Param("status") Integer status,
                       @Param("retryCount") Integer retryCount,
                       @Param("nextRetryTime") Date nextRetryTime);

    default List<MessageRecord> queryPendingMessages(Integer limit) {
        // 创建Lambda查询条件构造器
        LambdaQueryWrapper<MessageRecord> queryWrapper = new LambdaQueryWrapper<>();

        // 构建查询条件
        queryWrapper.in(MessageRecord::getStatus, MessageStatus.PENDING.getCode(),MessageStatus.TRYING.getCode()) // 状态等于待发送和尝试中
                .le(MessageRecord::getNextRetryTime, new Date())              // 下次重试时间小于等于当前时间
                .or()                                                         // 或者
                .isNull(MessageRecord::getNextRetryTime)                      // 下次重试时间为null
                .orderByAsc(MessageRecord::getCreateTime)                     // 按创建时间升序排序
                .last("LIMIT " + limit);                                      // 限制查询条数

        // 执行查询并返回结果列表
        return selectList(queryWrapper);
    }
}